package cn.wky.cale.calculate;

import android.content.Context;

import androidx.appcompat.app.AlertDialog;

import cn.wky.cale.calculate.lex.Lexer;
import cn.wky.cale.calculate.parser.Parser;

public class Calculator {
    private Context context;

    public Calculator(Context context) {
        this.context = context;
    }

    public String eval(String expr) {
        try {
            Lexer lexer = new Lexer(expr);
            Parser parser = new Parser(lexer);
            double value = parser.expression();
            return value + "";
        } catch (Parser.ParserException e) {
            showError(e.getMessage());
        }
        return null;
    }

    private void showError(String error) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setTitle("错误")
                .setMessage(error)
                .setPositiveButton("确定", null);
        builder.show();
    }
}
